import { getRequestHeaders, getApiPrefixV2 } from './request-tools';
import { HttpPortal } from '@shadom/portal-plugin-http';
import { define, transmit, use, defaultOptions } from '@shadom/portal';
import portals from './portals';
/**
 * 注册portal接口
 */
function registerPortal() {
    const api = process.env.VUE_APP_API || getApiPrefixV2();

    Object.assign(defaultOptions, {
        allowDupRequest: true,
        allowExternalKeys: false,
        requestFreezingTime: 400
    });
    
    for (let name in portals) {
        let portal = portals[name];
        // define定义接口，注册portal
        define({
            ...portal,
            type: portal.type ?? 'HttpPortal',
            name,
            uri: addHostToUri(api, portal.uri)
        });
    }
}

/**
 * 为uri拼接请求host，若Uri中带了https或http则不拼接
 * @param {string} uri 
 */
function addHostToUri(api, uri) {
    uri = uri ?? '';
    if (uri.indexOf('http') === -1 || uri.indexOf('https') === -1) {
        uri = api + uri;
    }
    return uri;
}

/**
 * 注册不同类型的PortalClass，如：
 * HttpPortal：http 类型
 * xxx: jsonp 类型
 * xxx: window.location类型
 * xxx: webscoket 类型
 */
function registerPortalClass() {
    // use 注册一个Portal类型 @param PortalClass
    use(HttpPortal);
}

registerPortalClass();
registerPortal();

/**
 * 获取数据,返回promise对象
 *
 * @param {Object} payload, 请求相关参数 {
 *	{string} name 数据分支的名称
 *  {string} uri 自定义uri
 * 	{Object} queries 请求的get参数对象,可选
 *  {Object} data 请求的post数据对象,可选
 *  {Object} value 待定
 *  {Object} headers 请求头
 * }
 * @return {Promise} promise
 */
const x = function (payload) {
    let headers = getRequestHeaders(payload.headers);
    return new Promise((resolve, reject) => {
        // transmit 发送接口请求
        transmit(payload.name, Object.assign({}, payload, { headers })).then(res => {
            const { data, raw } = res;
            if (data.status.code !== 200) {
                console.warn(`the ${raw.config.url} response data is `, data);
            }
            resolve(data);
        }).catch(err => {
            reject(err);
        });
    });
    // const res = await transmit(payload.name, Object.assign(headers, payload));
    // expect(res.raw.data).toBe('portal/post');
    // expect(res.data.token).toBe('112233');
};

export default {
    x
};
